package com.justech.mes.service;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class ReceiverMq {
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private RabbitMqSendService sendService;

    @RabbitListener(queues = {"message"})
    public void send_email(String msg, Message message, Channel channel) throws IOException {
        String s = new String(message.getBody(), "utf-8");
        JSONObject jsonObject = null;
        jsonObject = JSONObject.parseObject(s);
        String key = jsonObject.get("key").toString();
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
            sendService.send(s);
        } catch (Exception e) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            amqpTemplate.convertAndSend("", key, "@Wrong");
        }

    }
}
